package com.yuhs.zixing.study.springboot.redis;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @description: bean 的加载耗时
 * @author: yuhs
 * @date: 2022/5/9
 */
@Component
public class BeanInitCostTimeBeanPostProcessor implements BeanPostProcessor {

    private static final Log logger = LogFactory.getLog(BeanInitCostTimeBeanPostProcessor.class);

    private static final ConcurrentHashMap<String, Long> staterTime = new ConcurrentHashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        staterTime.put(beanName, System.currentTimeMillis());
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (Objects.nonNull(staterTime.get(beanName))) {
            logger.info("bean = " + beanName + " 加载耗时 = " + (System.currentTimeMillis() - staterTime.get(beanName)));
        }
        return bean;
    }
}
